import requests
import json
class AiApi():
    def __init__(self,window):
        self.window = window;
        self.url = 'http://127.0.0.1/v1/completion-messages'
        self.headers = {
            'Authorization': 'Bearer app-H42wbbXFI5qrE9IJs75zIHaA',
            'Content-Type': 'application/json',
        }
        self.data = {
            "inputs": {"query": "你好!"},
            "response_mode": "streaming",
            "user": "aiOps"
        }

    def sendMsg_(self,inputs):
        print("inputs: " + str(inputs))
        self.data["inputs"] = inputs;
        result = self.window.evaluate_js("startReponse()")
        allResponse = ""
        with requests.post(self.url, headers=self.headers, json=self.data, stream=True) as response:

            for line in response.iter_lines():
                # print(line)
                if line:
                    try:
                        data_str = line.decode('utf-8')
                        if "data: " not in data_str:
                            continue
                        json_str = data_str.split('data: ')[1]
                        data_dict = json.loads(json_str)
                        answer = data_dict.get('answer')
                        if answer is None:
                            continue
                        else:
                            msg = json.dumps(answer, ensure_ascii=False)[1:-1]
                            allResponse += msg;
                            result = self.window.evaluate_js("updateMsg(\"" + msg + "\")")
                    except Exception as e:
                        print(f"Caught exception: {e}")
        return allResponse;

    def sendMsg(self,query):
        print("query: "+query)
        self.data["inputs"]["query"] = query;
        result = self.window.evaluate_js("startReponse()")
        allResponse = ""
        with requests.post(self.url, headers=self.headers, json=self.data, stream=True) as response:
            for line in response.iter_lines():
                print(line)
                if line:
                    try:
                        data_str = line.decode('utf-8')
                        if "data: " not in data_str:
                            continue
                        json_str = data_str.split('data: ')[1]
                        data_dict = json.loads(json_str)
                        answer = data_dict.get('answer')
                        if answer is None:
                            continue
                        else:
                            msg = json.dumps(answer, ensure_ascii=False)[1:-1]
                            allResponse+=msg;
                            result = self.window.evaluate_js("updateMsg(\"" + msg + "\")")
                    except Exception as e:
                        print(f"Caught exception: {e}")
        return  allResponse;